package com.ltmonitor.web.controller.command;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.AlarmRecord;
import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.MediaItem;
import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.entity.TerminalParam;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.IMediaItemService;
import com.ltmonitor.service.ITerminalParamService;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.vo.PictureParam;

/**
 * 拍照/录像
 * 
 * @author DELL
 * 
 */

@Controller
@RequestMapping("/takePicture")
public class TakePictureAction extends TerminalCommandAction {

	@Autowired
	private IMediaItemService mediaItemService;

	@Autowired
	private ITerminalParamService terminalParamService;

	@RequestMapping("/view.action")
	public String view(long vehicleId, @RequestParam(defaultValue="0") long alarmId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		m.addAttribute("alarmId", alarmId);
		return "/command/takePicture";
	}

	/**
	 * 下发拍照指令
	 * @param vehicleId
	 * @param p 808协议的拍照参数类 PictureParam
	 * @param alarmId 报警处理的时候，如果处理方式是拍照，则要传入报警id, 以便于更新报警为已处理的状态
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage execute(long vehicleId,PictureParam p, @RequestParam(defaultValue="0") long  alarmId) {

		try {

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(JT808Constants.CMD_TAKE_PHOTO);
			tc.setCmdData(p.getCommandString());
			tc.setVehicleId(vehicleId);
			SendCommand(tc);

			if (alarmId > 0)
				this.processAlarm(alarmId, AlarmRecord.PROCESS_TAKE_PICTURE,"");
			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}

	}
	
	/**
	 * 设置定时拍照的参数,参见808协议文档的终端参数配置中关于定时拍照的参数说明
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/pictureOnTimer.action")
	public JsonMessage pictureOnTimer(String strTimerOn,
			String strUploadPic,int intervalType,int interval,String operation,String allSelectedVehicle,long vehicleId) {
		try {
			String cmdData = "" + 0x0064;
			StringBuilder sb = new StringBuilder();
			//String[] selectedChannel = strSelectedChannel.split(",");
			String[] takePictureOnTimer = strTimerOn.split(",");
			String[] uploadPic = strUploadPic.split(",");
			for (int m = 0; m < 8; m++) {
				boolean allowOnTimer = m < 5 ? takePictureOnTimer[m].equals("1") : false;
				sb.append(allowOnTimer ? 1 : 0);
			}

			for (int m = 0; m < 8; m++) {
				boolean b = m < 5 ? uploadPic[m].equals("1") : false;
				sb.append(b ? 1 : 0);
			}
			sb.append(intervalType);
			//将时间间隔转成二进制字符串
			String intervalBinString = Integer.toBinaryString((short) interval);
			StringBuilder sbInterval = new StringBuilder(intervalBinString);
			sb.append(sbInterval.reverse());
			int len = sb.length();
			if (len > 32) {
				sb.delete(32, len);
			} else if (len < 32) {
				while (len < 32) {
					sb.append(0);
					len++;
				}
			}
			sb.reverse();
			int paramValue = Integer.parseInt(sb.toString(), 2);
			cmdData += "," + paramValue;
			TerminalCommand tc = new TerminalCommand();
			tc.setVehicleId(vehicleId);
			if ("modify".equals(operation)) {
				tc.setCmdType(JT808Constants.CMD_CONFIG_PARAM);
				if ("on".equals(allSelectedVehicle)) {
					String REGISTER_KEY = "registerVehicleIds";
					List<Long> vehicleIdList = (List<Long>)super.getFromSession(REGISTER_KEY);
					if (vehicleIdList != null && vehicleIdList.size() > 1) {
						TerminalCommand command = new TerminalCommand();
						command.setCmdData(cmdData.toString());
						command.setCmdType(JT808Constants.CMD_CONFIG_PARAM);
						for (long vId : vehicleIdList) {
							if (vId != vehicleId)
								SendCommand(command, vId);
						}
					}
				}

			} else
				tc.setCmdType(JT808Constants.CMD_QUERY_PARAM);
			tc.setCmdData(cmdData.toString());
			SendCommand(tc);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	/**
	 * 获得终端参数中关于定时拍照的设置
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPictureConfig.action")
	public JsonMessage getPictureConfig(long vehicleId, long commandId) {
		TerminalParam tp = null;
		VehicleData vd = this.vehicleDataService.load(vehicleId);
		String code = "0x0064";
		if (commandId > 0) {
			String hsql = "from TerminalParam where commandId = ? and code = ? and simNo = ?";
			tp = (TerminalParam) this.terminalParamService.find(hsql,
					new Object[] { commandId, code, vd.getSimNo() });
		} else {
			String hsql = "from TerminalParam where code = ? and simNo = ?";
			tp = (TerminalParam) this.terminalParamService.find(hsql,
					new Object[] { code, vd.getSimNo() });
		}
		
		if(tp != null)
		{
			String str = tp.getValue();
			if(StringUtil.isNullOrEmpty(str) == false)
			{
				int value = Integer.parseInt(str);
				String binaryString = Integer.toBinaryString(value);
				while(binaryString.length() < 32)
				{
					binaryString = 0 + binaryString;
				}
				System.out.println(binaryString);
				StringBuilder b = new StringBuilder(binaryString);
				String strInterVal = b.substring(0,15);
				System.out.println(strInterVal);
				b = b.reverse();
				int interval = Integer.valueOf(strInterVal, 2);
				int ver = Integer.parseInt(b.substring(16,17));
				
				StringBuilder sb = new StringBuilder();
				for(int m = 0; m < 16; m++)
				{
					sb.append(b.charAt(m)).append(",");
				}
				sb.append(interval).append(",");
				sb.append(ver).append(",");
				sb.append(str);
				return json(true, sb.toString());
			}
		}
		return json(false,"");
	}

	
	/**
	 * 获取拍照上传结果
	 * 
	 * @return true表示执行结束，false代表正在执行
	 */
	@ResponseBody
	@RequestMapping("/getPictureResult.action")
	public JsonMessage getPictureResult(int commandId) {
		HashMap result = new HashMap();
		TerminalCommand tc = getTerminalCommand(commandId);

		BasicData bd = getBasicDataService().getBasicDataByCode(tc.getStatus(),
				"TCommandStatus");
		String status = bd != null ? bd.getName() : "";
		result.put("status", status);
		MediaItem mi = this.mediaItemService.getMediaItemByCommandId(commandId);
		if (TerminalCommand.STATUS_UPLOADED.equals(tc.getStatus())) {

			if (mi != null) {
				result.put("fileName", mi.getFileName());
				return json(true, result);
			} else {
				result.put("status", "没找到照片文件");
				return json(true, result);
			}
		}
		if (TerminalCommand.STATUS_SUCCESS.equals(tc.getStatus())) {
			status = "执行成功，等待上传";
			result.put("status", status);
			return json(false, status);
		} else if (TerminalCommand.STATUS_NEW.equals(tc.getStatus()) == false
				&& TerminalCommand.STATUS_PROCESSING.equals(tc.getStatus()) == false) {
			return json(true, result);
		} else
			return json(false, status);
	}

	public IMediaItemService getMediaItemService() {
		return mediaItemService;
	}

	public void setMediaItemService(IMediaItemService mediaItemService) {
		this.mediaItemService = mediaItemService;
	}

}
